angular.module('UCX.Cmis')
.directive('cloudReadingShare',(CmisService, localStorageService, ModelService,$window,$timeout, $uibModal, Utils, $translate)->

  scope:{
    file:'=',
    currentScope:'='
  }

  #  http://codepen.io/prophet_w/pen/GWjejg
  restrict:'C'
#  replace:true
  template:'
      <!-- Trigger the modal with a button -->
      <span ng-click="openShareModal(file)">

      </span>
      <!-- Modal -->
  '
  link:(scope, element, attr)->

    if !window.CloudReading
      window.CloudReading={}
    window.CloudReading.Utils =Utils
    window.CloudReading.translate =$translate
    lang = Utils.getLanguage()
    $translate.use lang
    scope.openModal = (file)->
      modalInstance = $uibModal.open({
        ariaLabelledBy: 'modal-title'
        ariaDescribedBy: 'modal-body'
        templateUrl: 'template-path/new-share.html',
        controller: 'ModalInstanceCtrl',
        controllerAs: '$ctrl',
#        windowClass:'cloud-reading-shared-modal'
        windowTopClass:'cloud-reading-shared-modal'
        backdropClass:'cloud-reading-shared-modal-backdrop'
        backdrop:'static'
        openedClass:'cloud-reading-shared-modal-open'
        resolve: {
          file: ()->
            file
        }
      })

    $('body .mailTo').on('click',()->
      Utils.sendGaEvent('Share setting','Social share','sendEmail')
    )



    scope.getObjectInfoById=(documentId,successfulCallback)->
      console.log("documentId: " + documentId)
      documentId = documentId.split(",")[0] # because cmis does not keep all doc versions.
      console.log("documentId: " + documentId)
      console.log(CmisService)
      console.log(CmisService.session)
      console.log(CmisService.session.defaultRepository)
      if CmisService.session && CmisService.session.defaultRepository
        CmisService.session.getObject(documentId,'latest',{
          includeACL: true
          includeAllowableActions:true
        }).ok (data)->
          successfulCallback && successfulCallback(data)
        .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
          console.log(error)
      else
        CmisService.session.loadRepositories().ok (res)->
          console.log 'repositroy'
          console.log res
          CmisService.session.defaultRepository = res['fxcld']
          localStorageService.set "rootFolderUrl" , res['fxcld']['rootFolderUrl']
          CmisService.session.getObject(documentId,'latest',{
            includeACL: true
            includeAllowableActions:true
          }).ok (data)->
            successfulCallback && successfulCallback(data)
          .notOk (error)->
            if Utils.handleCmis401Error(error)
              return
            console.log(error)
        .notOk((error)->
          if Utils.handleCmis401Error(error)
            return
          console.log(error)
        )
    scope.handleShareFromPhantom = ()->
      if !(WebPDF.ViewerInstance && WebPDF.ViewerInstance.getCMISObjectId && window.PhantomOnline && window.PhantomOnline.uploadToCMIS)
        console.log(WebPDF.ViewerInstance)
        console.log(WebPDF.ViewerInstance.getCMISObjectId)
        console.log window.PhantomOnline
        console.log window.PhantomOnline.uploadToCMIS
        return false

      # cmis file get cmisId
      documentId = WebPDF.ViewerInstance.getCMISObjectId()
#      if !documentId
#        if location.href.indexOf('object_id')>-1
#          url = location.href.split('?')[1]
#          urlObject = Utils.urlParaToObj(url)
#          console.log(urlObject)
#          documentId = urlObject['object_id']
#        else
#          documentId=''
      # local file has saved right now and has a cmisId from temp @var
      if !documentId
        if window.PhantomOnline
          localFileUuid = window.PhantomOnline.getUUID()
          if(window.PhantomOnline.uuidMapCmisId && window.PhantomOnline.uuidMapCmisId[localFileUuid])
            documentId = window.PhantomOnline.uuidMapCmisId[localFileUuid]
          else
            documentId=''
        else
          documentId=''

      uploadToCmis = (fileUrl,successfulCallback)->
        window.PhantomOnline.uploadToCMIS(fileUrl,(data)->
          successfulCallback && successfulCallback(data);
          console.log('======== succ data =========')
          console.log(data)
          if data.code == 0
            Utils.warning(data.message)
          if !data.succinctProperties
            data.succinctProperties = data.properties
          data.acl.aces =Utils.formatAcl(data.acl)
          if !data.allowableActions
            data.allowableActions = data.allowable_actions
          file = ModelService.createDocument(data)
          console.log('====share DocModified====');
          currentEmail = Utils.getCookie('currentEmail');
          if file.createdBy.id == currentEmail
            scope.openModal(file)
          else
            Utils.warning($translate.instant('only_owner_can_set_permission'))
        )
      # cmis file then get info
      if documentId
        Utils.connectCmis()
        if WebPDF.ViewerInstance.isDocModified()
          #save share file
          if !WebPDF.Engine.isJR
            console.log('====getDocumentUrl====')
            WebPDF.ViewerInstance.getDocumentUrl((fileUrl)->
              # 调用 webpdf 提供接口显示 uploading
              WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
              uploadToCmis(fileUrl,(data)->
                # 如果上传成功，调用webpdf方法，讲 modify flag 重置为 false
                WebPDF.ViewerInstance.setModifyState(false)
                WebPDF.closeWaiting();
              )
            ,
              ()->
                Utils.warning('Get Document Url Failed')
            )
          else
            console.log('====getDocumentBuffer====')
            WebPDF.ViewerInstance.getDocumentBuffer((fileArrayBuffer)->
              WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
              uploadToCmis(fileArrayBuffer,(data)->
                # 如果上传成功，调用webpdf方法，讲 modify flag 重置为 false
                WebPDF.ViewerInstance.setModifyState(false)
                WebPDF.closeWaiting();
              )
            ,
              ()->
                Utils.warning('Get Document Buffer Failed')
            )
        else
          scope.getObjectInfoById(documentId,(data)->
            file = ModelService.createDocument(data)
            currentEmail = Utils.getCookie('currentEmail');
            console.log('====share NOT DocModified====');
            console.log(documentId);
            console.log(data);
            console.log(file);
            console.log(currentEmail);
            if file.createdBy.id == currentEmail
              scope.openModal(file)
            else
              Utils.warning($translate.instant('only_owner_can_set_permission'))
          )
      else
        # not cmis file then upload
#        uploadToCmis = (fileUrl)->
#          window.PhantomOnline.uploadToCMIS(fileUrl,(data)->
#            console.log('======== succ data =========')
#            console.log(data)
#            if data.code == 0
#              Utils.warning(data.message)
#            if !data.succinctProperties
#              data.succinctProperties = data.properties
#            data.acl.aces =Utils.formatAcl(data.acl)
#            if !data.allowableActions
#              data.allowableActions = data.allowable_actions
#            file = ModelService.createDocument(data)
#            scope.openModal(file)
#          )
        Utils.connectCmis()
        if !WebPDF.Engine.isJR
          console.log('====getDocumentUrl====')
          WebPDF.ViewerInstance.getDocumentUrl((fileUrl)->
            WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
            uploadToCmis(fileUrl,(data)->
              WebPDF.ViewerInstance.setModifyState(false)
              WebPDF.closeWaiting();
            )
          ,
            ()->
              Utils.warning('Get Document Url Failed')
          )
        else
          console.log('====getDocumentBuffer====')
          WebPDF.ViewerInstance.getDocumentBuffer((fileArrayBuffer)->
            WebPDF.waiting(null, "fwr-ajax-loading", i18n.t("Load.Saving"));
            uploadToCmis(fileArrayBuffer,(data)->
              WebPDF.ViewerInstance.setModifyState(false)
              WebPDF.closeWaiting();
            )
          ,
            ()->
              Utils.warning('Get Document Buffer Failed')
          )

    scope.openShareModal = (file)->
      console.log(scope)
      console.log(file)
      console.log(localStorage.getItem('userInfo'))

      #  preview page
      if window.PhantomOnline
        if(!localStorage.getItem('userInfo'))
          # phantom 未登录
          if window.PhantomOnline && window.PhantomOnline.showSignInModal
            window.PhantomOnline.showSignInModal(()->
              scope.handleShareFromPhantom()
            )
            return true
        else
          # phantom 登录用户
          console.log('============>')
          console.log('============>')
          scope.handleShareFromPhantom()
          console.log window.location.href
      else if window.FX
        # 插件
        Utils.connectCmis()
        fileInfo = JSON.parse(localStorage.getItem('share_plugin_cmis_file'))
        console.log fileInfo
        cmisFileObj = ModelService.createDocument(fileInfo)
        scope.openModal cmisFileObj
      else
        #  not preview page
        #  every time the latest acl
        file.getAces(()->
          scope.openModal(file)
        ,(err)->
          console.log(err)
        ,true)


      #  modal style is here http://codepen.io/prophet_w/pen/KWqKgj?editors=1100
#      CmisService.getAces(file.id,(data)->
#
#      )

#    scope.$watch(()->
#      attr.id
#    ,()->
#      init()
#    )
)
.controller('ModalInstanceCtrl',($scope,file,$uibModalInstance,$timeout,$compile,$sce,Utils, $window, $uibPosition,CmisService, localStorageService, ApiService, ModelService, $translate)->
  $scope.file=file
  $scope.changed = false
  $scope.showSendEmail = true
  if window.FX && window.FX.app && window.FX.app.getInfo
    fxAppVersion = localStorage.getItem('share_plugin_app_version') || 10
    if(parseFloat(fxAppVersion) >= 1.1)
      $scope.showSendEmail = true
    else
      $scope.showSendEmail = false
  lang = Utils.getLanguage()
  if window.FX && window.FX.app && window.FX.app.getInfo
    lang = localStorage.getItem('share_plugin_lang').split('-')[1]
  $translate.use lang
  if(window.PhantomOnline && !currentUserId)
    currentUserId = localStorage.getItem('currentEmail')
  $scope.getSharedInfo = ()->
    ApiService.getSharedInfo(file,null,(sharedLink)->
      Utils.sendGaEvent('Document','Share file','getSharedInfo')
      console.log('========sharedLink=======')
      console.log(sharedLink)
      $scope.loading=false
      $scope.waitingForLink = false
      if sharedLink && sharedLink.can_download==1
        file.disableDownload = false
      else
        file.disableDownload = true
      $scope.disableDownload = file.disableDownload
#      file.sharedLink = sharedLink.phantom_online_url
#      https://jira.foxitsoftware.cn/browse/WEBPDF-5599
      file.sharedLink = sharedLink.short_url
      for item in file.aces
        if item.isDirect && item.userId!=file.createdBy.id
          file.description = {
            shareLink:sharedLink
          }

      $scope.fileLink = file.sharedLink


      $scope.hasSharedLink = true
      $scope.generateBigQrcode()
      $timeout(()->
        $scope.$apply()
      )
    ,
      (err)->
        $scope.loading=false
        Utils.warning(err)
        console.log err
        $timeout(()->
          $scope.$apply()
        )
    )

  if file.sharedLink
    $scope.hasSharedLink = true
    $scope.sharedLink = file.sharedLink
  else
    $scope.hasSharedLink = false
  $scope.disableDownload = file.disableDownload
  if !file.sharedLink
    $scope.waitingForLink = true
    $scope.getSharedInfo()


  console.log(CmisService)

  currentUserEmail = localStorageService.get('userEmail')

  $scope.everyonePermissionToActionMap={
    'smx:none':$translate.instant('special_people_can_view')
    'cmis:read':$translate.instant('anyone_has_link_can_view')
    'cmis:write':$translate.instant('anyone_has_link_can_comment')
  }
  $scope.permissionToActionMap={
    'cmis:read':$translate.instant('can_view')
#    'cmis:write':$translate.instant('can_comment')
  }

  ###
  #  user list begin
  ###
  fileOwner={
    userAvatar : file.createdBy.getAvatar()
    userId : file.createdBy.id
    action : $translate.instant('is_owner')
    isOwner:true
  }
  $scope.userList=[]
  $scope.userList.push(fileOwner)
  getActionByPermission = (permission)->
    return $scope.permissionToActionMap[permission] || $translate.instant('can_view')
  for ace in file.aces
    # 不显示 everyone 和 owner(现在判断cmis:all是 owner 并不是很准确 后期可能需要修改)
    if ace.userId!='everyone' && ace.permission!='cmis:all' && ace.userId!='guest'
      user={
        userId:ace.userId
        userAvatar:ace.user.getAvatar()
        permission:ace.permission
        action:getActionByPermission(ace.permission)
      }
      $scope.userList.push(user)
    #  user list

  $scope.getEveryonePermission=()->
    everyonePermission=[false,'smx:none']
    for ace in file.aces
      if (ace.userId=='everyone' && ace.isDirect==false) || (ace.userId=='guest' && ace.isDirect==false)
        everyonePermission=[false,ace.permission]
    for ace in file.aces
      if (ace.userId=='everyone' && ace.isDirect==true) || (ace.userId=='guest' && ace.isDirect==true)
        everyonePermission=[true,ace.permission]
    console.log('@@@@')
    console.log(everyonePermission)
    return everyonePermission

  $scope.defaultEveryonePermission = $scope.getEveryonePermission()[1] || 'smx:none'
  $scope.everyonePermission = $scope.getEveryonePermission()[1] || 'smx:none'
  $scope.setEveryonePermission = (cmisPermission)->
    $scope.everyonePermission = cmisPermission
    Utils.sendGaEvent('Share setting','Set everyone permission',cmisPermission)
    $scope.showChangeTips()

  $scope.showList = [
    $translate.instant('special_people')
    $translate.instant('anyone_has_link')
  ]
  $scope.selectedPermission = 'cmis:read'
  $scope.setGlobalAction = (cmisPermission)->
    $scope.selectedPermission = cmisPermission
    Utils.sendGaEvent('Share setting','Set user permission',cmisPermission)

  initData = ()->
  $scope.fileLink = file.sharedLink
  $scope.tooltipIsOpen = false
  $scope.copy_status = 'copied_success'
  $scope.errMsg = ''
  $scope.postMessage = ''
  $scope.elemVals={}

  $scope.newUser=[]
  $scope.deletedUser=[]
  $scope.changedUser = {
    originUser:$scope.userList
    newUser:$scope.newUser
    deletedUser:$scope.deletedUser
  }

  $scope.generateBigQrcode = ()->
    qrcodeHtml = $compile('<span qrcode width="120" height="120" url="'+$scope.fileLink+'"></span>')($scope)
    $scope.qrcodeHtml = $(qrcodeHtml[0]).html()
    #  $scope.qrcodeHtml = $sce.trustAsHtml('<b style="color: red">I can</b> have <div class="label label-success">HTML</div> content');
    #  $scope.qrcodeHtml = $sce.trustAsHtml(qrcodeHtml.html())
    $timeout(()->
      $('#popover-qrcode .popover-content').empty().append(qrcodeHtml[0])
    )
    $timeout(()->
      tinyQrcodeEle = $window.document.querySelector('#qrElement')
  #    bigQrcodeEle = $window.document.querySelector('#popover-qrcode')
  #    tinyQrcode={}
  #    bigQrcode={}
  #    bigQrcode.position = $uibPosition.position(bigQrcodeEle)
  #    tinyQrcode.position = $uibPosition.position(tinyQrcodeEle)
  #    console.log(tinyQrcode.position)
  #    console.log(bigQrcode.position)


      #  120 qrcode width 14 padding 2 border
  #    $scope.styles = {
  #      top:tinyQrcode.position.height+'px'
  #      left:tinyQrcode.position.left-Math.abs(120+14*2+4-tinyQrcode.position.width)/2+'px'
  #    }
      $scope.styles = {
        top:54+'px'
        left:212+'px'
      }
  #    console.log($scope.elemVals.position)
    ,300)
  $scope.generateBigQrcode()
  $scope.showBigQrcode = false
  $scope.hideQrcode = ()->
    $scope.showBigQrcode=false
  $scope.showQrcode = ()->
    $scope.showBigQrcode=true

  appSharedLink = {
    google:'https://plus.google.com/share?url='
    facebook:'https://www.facebook.com/share.php?u='
    twitter:'https://twitter.com/intent/tweet?text='
    linkedin:'https://www.linkedin.com/shareArticle?mini=true&url='
    weibo:'http://service.weibo.com/share/share.php?title='

  }
  $scope.getAppSharedApiLink = (appName)->
    appSharedLink[appName]
  $scope.shareTo = (appName,e)->

    if appName=="email"
      if window.FX && window.FX.app && window.FX.app.sendEmail
        if e
          e.stopPropagation()
          e.preventDefault()

        currentUserEmail = decodeURIComponent(localStorage.getItem('share_plugin_token'))
        currentUserEmail = currentUserEmail.split(',')[1]
        data = {
          "toRecipientList":"",
          "ccRecipientList":"",
          "subject":currentUserEmail+ " wants to share a document with you",
          "message":"Hi,\n I'd like to share "+ $scope.file.name+" with you using Foxit Document Sharing. clicking the link below to view the document:\n"+$scope.file.sharedLink+"\nSincerely,\n"+currentUserEmail
        }
        window.FX.app.sendEmail(data,(data)->

        )
        return false
      else
        return false

    appSharedApiLink = $scope.getAppSharedApiLink(appName)
    if CmisService.device == 'platform-pad'
      cordova.InAppBrowser.open(appSharedApiLink+$scope.fileLink, '_blank', 'hidden=no')
    else
#      if(appName == 'mailto')
#        window.location.href = $scope.getAppSharedApiLink(appName)+sharedLink
#      else
      top = (window.screen.height-365)/2
      left = (window.screen.width-650)/2

      window.open(
        appSharedApiLink+encodeURIComponent($scope.fileLink)
        appName
        "width=650,height=365,left="+left+",top="+top+",resizable,scrollbars=yes,status=1"
      )
    Utils.sendGaEvent('Share setting','Social share',appName)
    return true





  $scope.emailList = ()->
    return (user.userId for user in $scope.userList)

  $scope.validateEmail = ()->
    console.log('====validate email====')
    console.log($scope.newEmail)
    if $scope.newEmail==undefined || $scope.newEmail==''
      return true
    emailList = $scope.emailList()
    console.log('====emailList====')
    console.log(emailList)
    if !Utils.isValidEmail($scope.newEmail)
      $scope.errMsg = 'Not a valid email'
      $scope.errMsg = $translate.instant('not_valid_email')
      return false
    if emailList.indexOf($scope.newEmail) > -1
      $scope.errMsg = 'Email existed'
      $scope.errMsg = $translate.instant('email_existed')
      return false

    $scope.errMsg=''
    $scope.addEmail()
    return true


  $scope.addEmail = ()->
    newUser = {
      userId:$scope.newEmail
      userAvatar:'/img/ananymous-avatar.png'
      action:$scope.permissionToActionMap[$scope.selectedPermission]
      permission:$scope.selectedPermission
      isOwner:false
    }
    console.log(newUser)
    $scope.newUser.push(newUser)
    $scope.userList.push(newUser)
    $scope.showChangeTips()
    Utils.sendGaEvent('Share setting','Add email',$scope.newEmail)
    $scope.newEmail=''


  $scope.deleteEmail = (index)->
    Utils.sendGaEvent('Share setting','Remove email',$scope.userList[index]['userId'])
    $scope.userList.splice(index,1)
    $scope.showChangeTips()
    $scope.newUser
  $scope.changeDisableDownload = ()->
    $scope.changed=true
    $scope.showChangeTips()
  $scope.handleEnterKey=(e)->
    $scope.errMsg=''
    if e.which==13
      $scope.validateEmail()

  $scope.setUserAction = (user,cmisPermission)->
    user.action=$scope.permissionToActionMap[cmisPermission]
    user.permission=cmisPermission
    $scope.showChangeTips()
    Utils.sendGaEvent('Share setting','Change permission','')


  $scope.copyOnSuccess = (e)->
#    console.info('Action:', e.action)
#    console.info('Text:', e.text)
#    console.info('Trigger:', e.trigger)
#    e.clearSelection()
    timer = $timeout(()->
      $scope.copy_status = 'Copied'
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
    Utils.sendGaEvent('Share setting','Copy link',$scope.fileLink)
    console.log($scope.tooltipIsOpen)

  $scope.copyOnError = (e)->
#    console.error('Action:', e.action)
#    console.error('Trigger:', e.trigger)
    $timeout(()->
      $scope.copy_status = 'copy_failed'
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
  $scope.successSetShareInfoCallback = (data,file)->
    if(data.data && data.data.failed_share)
      if data.data.failed_share.length>0
        str=''
        for userName in data.data.failed_share
          str=userName+' '

      Utils.warning('Fail to share to '+str+'')
      console.log('====failed_share====')
      console.log(data.data.failed_share)

    data.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
    data.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
    newFile = ModelService.createDocument(data.data.cmis_document)
    console.log('=======new file======')
    console.log(newFile)
#    console.log('=======old file======')

    console.log(file)
#    file.getAces(null,null,true)
    callback = (cmisData)->
      if cmisData
        data=cmisData
      if window.FX && window.FX.app && window.FX.app.sendMessage
        window.FX.app.sendMessage(data)

      file.description = newFile.description
      file.aces = newFile.aces
      if data.data.share && data.data.share.can_download && data.data.share.can_download==1
        file.disableDownload = false
      else
        file.disableDownload = true
      $timeout(()->
        $scope.$apply()
      )
      console.log('======done======')
      # ga and
      Utils.sendGaEvent('Share setting','Save Changes','')
      Utils.success($translate.instant('set_share_suc'))
      $scope.settingShareInfo = false
      if (window.formPreviewAndShare && window.formPreviewAndShare == true && window.parent && window.parent.document.getElementById('cloud-reading-iframe'))
        console.log("reload cloud reading iframe")
        window.parent.document.getElementById('cloud-reading-iframe').contentWindow.location.reload(true)

      # close modal
      if(window.FX && window.FX.app && window.FX.app.closeDialog)
        FX.app.closeDialog()
      $uibModalInstance.close()

    if file.getShareCode()
      ApiService.setDownloadPerm(file.getShareCode(),$scope.disableDownload,(data)->
        console.log('set download perm succ')
        console.log(data)
        callback(data)
      ,(data)->
        console.log('set download perm fail')
        console.log()
        callback()
      )
    else
      callback()





  $scope.setShareInfo = (file,shareInfo,postMessage,disableDownload)->
    ApiService.setSharedInfo(file,shareInfo,postMessage,disableDownload,(data)->
      $scope.successSetShareInfoCallback(data,file)
    ,(errData)->
      $scope.settingShareInfo = false
      $timeout(()->
        $scope.$apply()
      )
    )
  $scope.ok = ()->
#    if($scope.newEmail!='')
#      $scope.validateEmail()
    # 发送的 请求 只关注 两个  一个是新增用户 一个是删除的用户
    if $scope.settingShareInfo == true
      return false

    if $scope.validateEmail()==false
      return

    if !$scope.changed
      if window.FX && window.FX.app && window.FX.app.closeDialog
        FX.app.closeDialog()
      $uibModalInstance.close()
      return
    $scope.settingShareInfo = true
    shareInfo=[]
    everyoneData = {
      "guest": $scope.everyonePermission
    }
    if $scope.everyonePermission != 'smx:none'
      shareInfo.push(everyoneData)
    userList = angular.copy($scope.userList)
    userList.shift()
    for user in userList
      arr={}
      key = user.userId
#      value = user.permission
      value = 'cmis:read'
      arr[key]=value
      shareInfo.push(arr)
    console.log('defaultEveryonePermission',$scope.defaultEveryonePermission)
    console.log('everyonePermission',$scope.everyonePermission)
    console.log('everyoneData',everyoneData)
    console.log('shareInfo',shareInfo)
    console.log('postMessage',$scope.postMessage)
    console.log('$scope.userList',$scope.userList)

    if shareInfo.length>=0
      if $scope.postMessage
        Utils.sendGaEvent('Share setting','Email content','')
      $scope.setShareInfo(file,shareInfo,$scope.postMessage,$scope.disableDownload)
      return true

  $scope.showChangeTips = ()->

    $('.modal-footer .alert.alert-success').removeClass('hide')
    $scope.changed = true
  $scope.closeChangeTips = ()->
    $('.modal-footer .alert.alert-success').addClass('hide')
    return false

  $scope.cancel = ()->
    Utils.sendGaEvent('Share setting','Click cancel button','close share modal')
    if(window.FX && window.FX.app && window.FX.app.closeDialog)
      FX.app.closeDialog()
    $uibModalInstance.close()


  if !$.fn.dropdown
    clearMenus = (e) ->
      if e and e.which == 3
        return
      $(backdrop).remove()
      $(toggle).each ->
        $this = $(this)
        $parent = getParent($this)
        relatedTarget = relatedTarget: this
        if !$parent.hasClass('open')
          return
        $parent.trigger e = $.Event('hide.bs.dropdown', relatedTarget)
        if e.isDefaultPrevented()
          return
        $this.attr 'aria-expanded', 'false'
        $parent.removeClass('open').trigger 'hidden.bs.dropdown', relatedTarget
        return
      return

    getParent = ($this) ->
      selector = $this.attr('data-target')
      if !selector
        selector = $this.attr('href')
        selector = selector and /#[A-Za-z]/.test(selector) and selector.replace(/.*(?=#[^\s]*$)/, '')
      # strip for ie7
      $parent = selector and $(selector)
      if $parent and $parent.length then $parent else $this.parent()

  # DROPDOWN PLUGIN DEFINITION
  # ==========================

    Plugin = (option) ->
      @each ->
        $this = $(this)
        data = $this.data('bs.dropdown')
        if !data
          $this.data 'bs.dropdown', data = new Dropdown(this)
        if typeof option == 'string'
          data[option].call $this
        return

    'use strict'
  # DROPDOWN CLASS DEFINITION
  # =========================
    backdrop = '.dropdown-backdrop'
    toggle = '[data-toggle="dropdown"]'

    Dropdown = (element) ->
      $(element).on 'click.bs.dropdown', @toggle
      return

    Dropdown.VERSION = '3.3.4'

    Dropdown::toggle = (e) ->
      $this = $(this)
      if $this.is('.disabled, :disabled')
        return
      $parent = getParent($this)
      isActive = $parent.hasClass('open')
      clearMenus()
      if !isActive
        if 'ontouchstart' of document.documentElement and !$parent.closest('.navbar-nav').length
  # if mobile we use a backdrop because click events don't delegate
          $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on 'click', clearMenus
        relatedTarget = relatedTarget: this
        $parent.trigger e = $.Event('show.bs.dropdown', relatedTarget)
        if e.isDefaultPrevented()
          return
        $this.trigger('focus').attr 'aria-expanded', 'true'
        $parent.toggleClass('open').trigger 'shown.bs.dropdown', relatedTarget
      false

    Dropdown::keydown = (e) ->
      if !/(38|40|27|32)/.test(e.which) or /input|textarea/i.test(e.target.tagName)
        return
      $this = $(this)
      e.preventDefault()
      e.stopPropagation()
      if $this.is('.disabled, :disabled')
        return
      $parent = getParent($this)
      isActive = $parent.hasClass('open')
      if !isActive and e.which != 27 or isActive and e.which == 27
        if e.which == 27
          $parent.find(toggle).trigger 'focus'
        return $this.trigger('click')
      desc = ' li:not(.disabled):visible a'
      $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
      if !$items.length
        return
      index = $items.index(e.target)
      if e.which == 38 and index > 0
        index--
      # up
      if e.which == 40 and index < $items.length - 1
        index++
      # down
      if ! ~index
        index = 0
      $items.eq(index).trigger 'focus'
      return

    old = $.fn.dropdown
    $.fn.dropdown = Plugin
    $.fn.dropdown.Constructor = Dropdown
  # DROPDOWN NO CONFLICT
  # ====================

    $.fn.dropdown.noConflict = ->
      $.fn.dropdown = old
      this

  # APPLY TO STANDARD DROPDOWN ELEMENTS
  # ===================================
    $(document).on('click.bs.dropdown.data-api', clearMenus).on('click.bs.dropdown.data-api', '.dropdown form', (e) ->
      e.stopPropagation()
      return
    ).on('click.bs.dropdown.data-api', toggle, Dropdown::toggle).on('keydown.bs.dropdown.data-api', toggle, Dropdown::keydown).on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown::keydown).on 'keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown::keydown
    return

# ---
# generated by js2coffee 2.2.0
)
